#!/usr/bin/python3
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-

# Copyright (c) 2005-2014 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

import os
import sys
import barkspider


def usage():
    print('Usage:')
    print('   barkspider status [-l|--full]')
    print('   barkspider robustify <application-name>|all')
    print('   barkspider resume <application-name>|all')
    print('   barkspider refresh')
    print('')
    print('Supported application(s):')
    print('   %s' % (", ".join(barkspider.SystemContext().get_app_names())))
    print('')


def die(msg):
    print(msg, file=sys.stderr)
    sys.exit(1)


def doShow():
    if len(sys.argv) >= 3 and sys.argv[2] in ["-l", "--full"]:
        bInstalledOnly = False
    else:
        bInstalledOnly = True

    s1 = "Application      "
    s2 = "Status                 "
    s3 = "Last Update            "
    s4 = "Message"
    print(s1 + s2 + s3 + s4)

    ctx = barkspider.SystemContext()
    for app in ctx.get_app_names(bInstalledOnly):
        app_stat, msg, last_update_time = ctx.get_app_info(app)

        app_stat = str(app_stat)

        if msg is None:
            msg = ""

        if last_update_time is not None:
            last_update_time = last_update_time.strftime("%Y-%m-%d %H:%M:%S")
        else:
            last_update_time = ""

        print(app + \
              " " * (len(s1) - len(app)) + \
              app_stat + \
              " " * (len(s2) - len(app_stat)) + \
              last_update_time + \
              " " * (len(s3) - len(last_update_time)) + \
              msg)


def doOptimize():
    if os.getuid() != 0:
        die("You must run this command as root!")

    if len(sys.argv) < 3:
        die("No application specified!")

    ctx = barkspider.SystemContext()

    if sys.argv[2] == "all":
        appNameList = []
        for app in ctx.get_app_names():
            app_stat, msg, last_update_time = ctx.get_app_info(app)
            if app_stat == barkspider.AppStat.NOT_INSTALLED:
                continue
            appNameList.append(app)
    else:
        if sys.argv[2] not in ctx.get_app_names():
            die("Application \"%s\" is not supported by barkspider!" % (sys.argv[2]))
        appNameList = [sys.argv[2]]

    ctx.robustify_app_config(appNameList)


def doResume():
    die("Currently there's no way to resume config robustified by barkspider!")


def doRefresh():
    if os.getuid() != 0:
        die("You must run this command as root!")

    ctx = barkspider.SystemContext()
    ctx.refresh_app_config()


if __name__ == '__main__':
    if len(sys.argv) <= 1:
        usage()
        sys.exit(1)

    if sys.argv[1] == "--help":
        usage()
        sys.exit(0)

    op = sys.argv[1]
    if op == "status":
        doShow()
    elif op == "robustify":
        doOptimize()
    elif op == "resume":
        doResume()
    elif op == "refresh":
        doRefresh()
    else:
        die('Invalid operation.')
